import { defineStore } from 'pinia'
import type { JSJLStore } from '../../types/JSJL/JSJLStore'

/**
 * 教师交流帖子存储模块
 * 负责管理教师交流帖子的全局状态
 */
export const useTeachingPostStore = defineStore('teachingPost', {
    // 持久化配置
    persist: {
        storage: localStorage,  // 使用localStorage作为存储介质
        paths: ['postList', 'currentPost']
    },
    state: () => ({
        // 所有帖子列表
        postList: [] as JSJLStore[],
        // 当前选中的帖子详情
        currentPost: null as JSJLStore | null,
        // 加载状态
        loading: false,
        // 分页信息
        pagination: {
            currentPage: 1,
            pageSize: 10,
            total: 0
        },
        // 错误信息
        error: null as string | null
    }),

    actions: {
        /**
         * 获取帖子列表（带分页和搜索）
         * @param params - 查询参数 { page, pageSize, keyword, descending }
         */
        async fetchPosts(params?: {
            page?: number
            pageSize?: number
            keyword?: string
            descending?: boolean
        }) {
            this.loading = true
            this.error = null
            try {
                // const res = await postApi.getPosts(params)
                // this.postList = res.data.list
                // this.pagination = {
                //     currentPage: res.data.page,
                //     pageSize: res.data.pageSize,
                //     total: res.data.total
                // }
            } catch (err) {
                this.error = err.message || '获取帖子列表失败'
                throw err
            } finally {
                this.loading = false
            }
        },

        /**
         * 获取帖子详情
         * @param postId - 帖子ID
         */
        async fetchPostDetail(postId: number) {
            this.loading = true
            this.error = null
            try {
                // const res = await postApi.getPostById(postId)
                // this.currentPost = res.data
            } catch (err) {
                this.error = err.message || '获取帖子详情失败'
                throw err
            } finally {
                this.loading = false
            }
        },

        /**
         * 创建新帖子
         * @param newPost - 新帖子数据
         */
        async createPost(newPost: Omit<JSJLStore, 'postId' | 'createTime' | 'updateTime' | 'isDeleted'>) {
            this.loading = true
            this.error = null
            try {
                // const created = await postApi.createPost(newPost)
                // this.postList.unshift(created)
                // return created
            } catch (err) {
                this.error = err.message || '创建帖子失败'
                throw err
            } finally {
                this.loading = false
            }
        },

        /**
         * 更新帖子
         * @param postId - 帖子ID
         * @param updateData - 更新数据
         */
        async updatePost(postId: number, updateData: Partial<JSJLStore>) {
            this.loading = true
            this.error = null
            try {
                // const updated = await postApi.updatePost(postId, updateData)
                // 更新列表中的帖子
                const index = this.postList.findIndex(p => p.postId === postId)
                if (index !== -1) {
                    this.postList[index] = { ...this.postList[index], ...updateData }
                }
                // 更新当前帖子
                if (this.currentPost?.postId === postId) {
                    this.currentPost = { ...this.currentPost, ...updateData }
                }
                return updated
            } catch (err) {
                this.error = err.message || '更新帖子失败'
                throw err
            } finally {
                this.loading = false
            }
        },

        /**
         * 删除帖子（逻辑删除）
         * @param postId - 帖子ID
         */
        async deletePost(postId: number) {
            this.loading = true
            this.error = null
            try {
                // await postApi.deletePost(postId)
                // 更新列表中的帖子状态
                const index = this.postList.findIndex(p => p.postId === postId)
                if (index !== -1) {
                    this.postList[index].isDeleted = 1
                }
                // 更新当前帖子状态
                if (this.currentPost?.postId === postId) {
                    this.currentPost.isDeleted = 1
                }
            } catch (err) {
                this.error = err.message || '删除帖子失败'
                throw err
            } finally {
                this.loading = false
            }
        }
    },

    getters: {
        /**
         * 获取热门帖子（按评论数排序）
         */
        popularPosts(state): JSJLStore[] {
            return [...state.postList]
                .filter(post => post.isDeleted === 0)
                .sort((a, b) => (b.commentCount || 0) - (a.commentCount || 0))
                .slice(0, 5)
        },

        /**
         * 根据作者ID获取帖子
         * @param authorId - 作者ID
         */
        postsByAuthor: (state) => (authorId: number) => {
            return state.postList.filter(
                post => post.authorId === authorId && post.isDeleted === 0
            )
        },

        /**
         * 获取当前用户的帖子
         */
        myPosts(state): JSJLStore[] {
            // 假设从用户存储中获取当前用户ID
            // const userId = useUserStore().userId
            // return this.postsByAuthor(userId)
            return []
        }
    }
})
